package com.colin.action;

import com.colin.ui.component.CssPattern;
import com.intellij.openapi.editor.colors.ColorKey;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.sun.istack.NotNull;
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.events.StartLoadingEvent;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class BrowserFactory
        implements ToolWindowFactory {

    private final JPanel jPanel = new JPanel(new BorderLayout());
    private final JProgressBar progressBar = new JProgressBar();
    private final Browser browser = new Browser(BrowserType.LIGHTWEIGHT, new BrowserContext(new BrowserContextParams(".\\data")));
    private final BrowserView view = new BrowserView(browser);
    private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private ToolWindow toolWindow;
    private final LoadAdapter loadAdapter = new LoadAdapter() {
        @Override
        public void onStartLoadingFrame(StartLoadingEvent event) {
            onload();
        }

        @Override
        public void onFinishLoadingFrame(FinishLoadingEvent event) {
            onSuccess();
        }
    };

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        // 获取内容工厂的实例
        ContentFactory contentFactory = ContentFactory.getInstance();
        // 获取 ToolWindow 显示的内容
        Content content = contentFactory.createContent(
                this.openWebPage(),
                "", false);
        // 设置 ToolWindow 显示的内容
        ContentManager contentManager = toolWindow.getContentManager();
        contentManager.addContent(content);
        this.toolWindow = toolWindow;
    }

    public JComponent openWebPage() {
        // 谷歌内核浏览器
        browser.setContextMenuHandler(new MyContextMenuHandler(view));
        browser.setPopupHandler((popupParams) -> {
            onload();
            browser.loadURL(popupParams.getURL());
            return null;
        });
        browser.setZoomEnabled(true);
        browser.addLoadListener(loadAdapter);
        JPanel urlPanel = new JPanel(new GridLayout(1, 4));
        urlPanel.add(new JLabel("地址:"));
        JTextField urlTextField = new JTextField();
        urlPanel.add(urlTextField);
        urlPanel.add(getFastButtonRedirect("https://www.zhihu.com/", "知乎"));
        urlPanel.add(getFastButtonRedirect("https://www.baidu.com/", "百度"));
        urlPanel.add(buildClearMode());
        urlPanel.add(buildAdaptMode());
        urlTextField.addActionListener(
                event -> {
                    onload();
                    String url = urlTextField.getText();
                    browser.loadURL(url);
                }
        );
        // 加载地址
        EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
        Color backgroundColor = scheme.getColor(ColorKey.find(EditorColors.GUTTER_BACKGROUND.getExternalName()));
        jPanel.setBackground(backgroundColor);
        jPanel.add(urlPanel, BorderLayout.NORTH);
        jPanel.setVisible(true);
        return jPanel;
    }

    private static void refreshTheme(Browser browser) {
        EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
        Color backgroundColor = scheme.getColor(ColorKey.find(EditorColors.GUTTER_BACKGROUND.getExternalName()));
        Color fontColor = EditorColorsManager.getInstance().getGlobalScheme().getColor(ColorKey.find(EditorColors.CARET_COLOR.getExternalName()));
        assert backgroundColor != null && fontColor != null;
        browser.executeJavaScript(getFormat(backgroundColor, fontColor));
    }

    private JButton getFastButtonRedirect(String url, String name) {
        JButton button = new JButton(name);
        button.setToolTipText(url);
        button.addActionListener(e -> {
            onload();
            browser.loadURL(url);
        });
        return button;
    }

    private JButton buildClearMode() {
        JButton button = new JButton("原始页面");
        button.addActionListener(e -> {
            scheduledExecutorService.shutdown();
            browser.reload();
        });
        return button;
    }

    private JButton buildAdaptMode() {
        JButton button = new JButton("主题适配");
        button.addActionListener(e -> {
            // 添加定时任务
            scheduledExecutorService.scheduleAtFixedRate(() -> refreshTheme(browser), 1, 1, TimeUnit.SECONDS);
            browser.reload();
        });
        return button;
    }

    private static String getFormat(Color backgroundColor, Color fontColor) {
        return String.format(CssPattern.BLACK_CSS,
                backgroundColor.getRed(),
                backgroundColor.getGreen(),
                backgroundColor.getBlue(),
                backgroundColor.getAlpha(),
                fontColor.getRed(),
                fontColor.getGreen(),
                fontColor.getBlue(),
                fontColor.getAlpha()
        );
    }

    private void onload() {
        jPanel.remove(view);
        progressBar.setIndeterminate(true);
        jPanel.add(progressBar);
        jPanel.repaint();
    }

    private void onSuccess() {
        jPanel.remove(progressBar);
        jPanel.add(view);
        jPanel.repaint();

        // 设置网页大小自适应
        browser.setZoomEnabled(true);
        browser.setZoomLevel(0.0); // 设置缩放级别为0，即自适应
    }

    /**
     * 页面内右键菜单
     */
    private static class MyContextMenuHandler implements ContextMenuHandler {

        private final JComponent component;

        private MyContextMenuHandler(JComponent parentComponent) {
            this.component = parentComponent;
        }

        public void showContextMenu(final ContextMenuParams params) {
            final JPopupMenu popupMenu = new JPopupMenu();
            final Browser browser = params.getBrowser();
            popupMenu.add(createMenuItem("刷新", browser::reload));
            popupMenu.add(createMenuItem("前进", browser::goForward));
            popupMenu.add(createMenuItem("后退", browser::goBack));

            final Point location = params.getLocation();
            SwingUtilities.invokeLater(() -> popupMenu.show(component, location.x, location.y));
        }

        private static JMenuItem createMenuItem(String title, final Runnable action) {
            JMenuItem reloadMenuItem = new JMenuItem(title);
            reloadMenuItem.addActionListener(e -> action.run());
            return reloadMenuItem;
        }
    }
}
